<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-breadcrumb>
              <a-breadcrumb-item href="">
                <a-icon type="home" />
                <span>首页</span>
              </a-breadcrumb-item>
              <a-breadcrumb-item href="">
                <a-icon type="user" />
                <span>合同管理</span>
              </a-breadcrumb-item>
              <a-breadcrumb-item href="">
                <span>
                <template v-if="this.id !== ''"> <a-icon type="edit" />合同复制</template>
                  <template v-else> <a-icon type="folder-add" />合同添加</template>
                </span>
              </a-breadcrumb-item>
            </a-breadcrumb>
          </a-col>
          <a-col :span="24">&nbsp;</a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <div class="table-page-search-wrapper">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :span="16">
            <a-form-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-button-group>
                <a-button type="primary" @click="goBack"> <a-icon type="left" />返回 </a-button>
                <a-button type="primary" @click="toSave">保存 <a-icon type="right" /></a-button>
              </a-button-group>
            </a-form-item>
          </a-col>
          <a-col :span="8" :style="{ textAlign: 'right' }">
            <a-form-item>
              <a-button-group>
                <a-button type="primary" :disabled="disabledAudit"  @click="toAudit"> <a-icon type="left" />审批 </a-button>
              </a-button-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">

          <a-col :span="8">
            <a-form-item label="id" hidden="true">
              <a-input v-decorator="['id']" />
            </a-form-item>
            <a-form-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['code']" :disabled="disabledOne" readOnly placeholder="请输入编号"></a-input>
            </a-form-item>
            <a-form-item label="合同号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['contractCode', validatorRules.contractCode]" placeholder="请输入合同号"></a-input>
            </a-form-item>
            <a-form-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['contractName', validatorRules.contractName]" placeholder="请输入合同名称"></a-input>
            </a-form-item>
            <a-form-item label="主责部门id" hidden="true">
              <a-input v-decorator="['mainDepartId']" hidden="true" placeholder="请输入主责部门id"></a-input>
            </a-form-item>
            <a-form-item label="主责部门名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['mainDepart']"  readOnly @click="onSearchDepart" placeholder="请输入主责部门名称">
                <a-icon slot="prefix" type="bars"/>
              </a-input>
            </a-form-item>
            <a-form-item label="招标单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['tenderNumber']" readOnly placeholder="请输入招标单号" >
                <a-icon slot="prefix" type="bars"/>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="供货商编号" hidden="true">
              <a-input v-decorator="['supplierCode']" placeholder="请输入供货商编号" ></a-input>
            </a-form-item>
            <a-form-item label="供货商名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['supplierName', validatorRules.supplierName]" readOnly @click="onSearchSupplier" placeholder="请输入供应商名称">
                <a-icon slot="prefix" type="bars"/>
              </a-input>
            </a-form-item>
            <a-form-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['createBy']" readOnly :disabled="disabledOne" placeholder="请输入负责人"></a-input>
            </a-form-item>
            <a-form-item label="合同起始时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择合同起始时间" :dateFormat="dateFormat" v-decorator="['startTime', validatorRules.startTime]" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
            <a-form-item label="合同终止时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择合同终止时间" :dateFormat="dateFormat" v-decorator="['endTime', validatorRules.endTime]" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="合同类别" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                placeholder="请选择合同类别"
                :triggerChange="true"
                dictCode="contract_category" @change="handleChange"
                v-decorator="['contractCategory', validatorRules.contractCategory]"
              />
            </a-form-item>
            <a-form-item label="合同编制时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择合同编制时间" readOnly showTime :dateFormat="dateFormat" v-decorator="['compileTime']" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
            <a-form-item label="年度" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['year', validatorRules.year]" placeholder="请输入年度"></a-input>
            </a-form-item>
            <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['status']" readOnly :disabled="disabledOne" placeholder="请输入状态"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">

    </div>

    <!-- table区域-begin -->
    <div>
      <a-tabs default-active-key="1">
        <a-tab-pane key="1">
      <span slot="tab">
        <a-icon type="tablet" />
        合同明细
      </span>
          <a-button class="editable-add-btn" @click="handleAdd">
            添加
          </a-button>
          <a-table ref="table" bordered :data-source="dataSource" :columns="columns">
            <template slot="action" slot-scope="text, record">
              <a @click="() => handleEdit(record)">编辑</a>
              <a-divider type="vertical"/>
              <a-popconfirm title="确定删除吗?" @confirm="() => deleteNow(record)">
                <a href="javascript:;">删除</a>
              </a-popconfirm>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2">
      <span slot="tab">
        <a-icon type="transaction" />
        付款计划
      </span>
          <a-button class="editable-add-btn" @click="handleAdd">
            添加
          </a-button>
          <a-table ref="table" bordered :data-source="payPlanDataSource" :columns="payPlanColumns"></a-table>
        </a-tab-pane>
      </a-tabs>
    </div>
    <depart-tree-modal ref="departModel" @ok="onDepartOk"></depart-tree-modal>
    <supplier-list-modal ref="supplierModal" @ok="onSupplierOk"></supplier-list-modal>
    <mms-contract-material-modal ref="materialForm" @ok="modalFormOk"></mms-contract-material-modal>
    <mms-contract-asset-modal ref="assetForm" @ok="modalFormOk"></mms-contract-asset-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@lone/lone-vue/src/utils/mixin'
  import JDate from '@lone/lone-vue/src/components/jeecg/JDate'
  import { postAction, putAction, deleteAction, getAction } from '@lone/lone-vue/src/api/manage'
  import SupplierListModal from '../base/form/SupplierListModal'
  import DepartTreeModal from '../base/form/DepartTreeModal'
  import Vue from 'vue'
  import MmsContractMaterialModal from './form/MmsContractMaterialModal'
  import MmsContractAssetModal from './form/MmsContractAssetModal'

  const checkContractCode = (params)=>getAction("/base/mmsContract/verifyContractCodeUnique",params);

  export default {
    name: 'MmsContractCloneDetailsList',
    mixins:[ mixinDevice],
    components: {
      MmsContractAssetModal,
      MmsContractMaterialModal,
      JDate,
      SupplierListModal,
      DepartTreeModal
    },
    props:{
      //判断是编辑还是新增
      status:{
        type:String,
        required:false
      },
      //判断是编辑Id
      id:{
        type:String,
        required:false
      },
    },
    watch:{
      status: {
        handler(newVal, oldVal) {
          this.loadFormData()
        },
        immediate: true
      }
    },
    data () {
      return {
        description: 'mms_contract_details管理页面',
        top: 10,
        dateFormat: 'YYYY-MM-DD HH:mm:ss',
        // 表头
        disabledAll: false,
        disabledOne: false,
        editingKey: '',
        dataSource: [],
        payPlanDataSource: [],
        form: this.$form.createForm(this),
        model: {},
        disabledAudit: false,
        statusMethod: '',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules:{
          contractCode: {rules: [{ required: true, message: '合同号已存在',validator: this.validateContractCode
            }]},
          contractName: {rules: [{required: true, message: '请输入合同名称', trigger: 'change' }]},
          startTime: {rules: [{required: true, message: '请输入合同起始时间', trigger: 'change' }]},
          endTime: {rules: [{required: true, message: '请输入合同终止时间', trigger: 'change' }]},
          year: {rules: [{required: true, message: '请输入年度', trigger: 'change' }]},
          contractCategory: {rules: [{required: true, message: '请输入合同类别', trigger: 'change' }]},
          supplierName: {rules: [{required: true, message: '请输入供货商', trigger: 'change' }]}
        },
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'物资编码',
            align:"center",
            dataIndex: 'materialCode'
          },
          {
            title:'物资名称',
            align:"center",
            dataIndex: 'materialName'
          },
          {
            title:'规格',
            align:"center",
            dataIndex: 'specs'
          },
          {
            title:'型号',
            align:"center",
            dataIndex: 'model'
          },
          {
            title:'预估数量',
            align:"center",
            dataIndex: 'evaluateNumber'
          },
          {
            title:'单价',
            align:"center",
            dataIndex: 'price'
          },
          {
            title:'计量单位',
            align:"center",
            dataIndex: 'unit'
          },
          {
            title:'品牌名称',
            align:"center",
            dataIndex: 'brand'
          },
          {
            title:'供应商编码',
            align:"center",
            dataIndex: 'supplierCode'
          },
          {
            title:'供应商名称',
            align:"center",
            dataIndex: 'supplierName'
          },
          {
            title: '操作',
            dataIndex: 'id',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        payPlanColumns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          }
        ],
        dictOptions:{},
      }
    },
    created() {
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      validateContractCode(rule, value, callback){
        let params = {
          // id: this.form.getFieldValue('id'),
          contractCode: value
        };
        if(!value){
          callback('请输入合同号');
          return;
        }
        checkContractCode(params).then((res)=>{
          if(res.success){
            callback();
          }else{
            callback(rule.message);
          }
        });
      },
      onSearchSupplier (){
        this.$refs.supplierModal.showSupplierInfo();
      },
      onSupplierOk (selectionRows, num) {
        this.form.setFieldsValue({supplierName: selectionRows.name})
        this.form.setFieldsValue({supplierCode: selectionRows.code})
      },
      onSearchDepart (){
        this.$refs.departModel.showSelectDepartTreeModal('ok');
      },
      onDepartOk (selectionRows, num) {
        this.form.setFieldsValue({mainDepartId: selectionRows.key})
        this.form.setFieldsValue({mainDepart: selectionRows.label})
      },
      handleChange(value) {
        let that = this;
        if(value === 'wz_contract' || value === 'ticket_contract'){
          that.columns.splice(1,1, {
            title:'物资编码',
            align:"center",
            dataIndex: 'materialCode'
          });
          that.columns.splice(2,1, {
            title:'物资名称',
            align:"center",
            dataIndex: 'materialName'
          });
        }else if(value === 'asset_contract'){
          that.columns.splice(1,1, {
            title:'资产分类',
            align:"center",
            dataIndex: 'assetCategory'
          });
          that.columns.splice(2,1, {
            title:'资产名称',
            align:"center",
            dataIndex: 'assetName'
          });
        }
      },
      loadFormData() {
        let that = this;
        this.dataSource = [];
        getAction('/base/mmsMaterialCode/getUserInfo', {}).then((res) => {
          if (res.success) {
            let result = res.result;
            if(result){
              this.form.setFieldsValue({createBy: result['realname']})
            }
          }
        })
        if(this.status === 'C'){
          that.statusMethod = 'COPY'
        }else if(this.status === 'R'){
          that.statusMethod = 'ADD'
        }
        if(this.id !== ''){
          let paramsObject = {id: this.id, statusMethod: that.statusMethod};
          getAction('/base/mmsContract/queryContractById', paramsObject).then((res) => {
            if (res.success) {
              let result = res.result;
              Vue.prototype.$copyProperties(that.form, result,{status: '新建', contractCategory: 'wz_contract',
                compileTime: Vue.prototype.$formatDate()}, that.dataSource);
              if(result && result['status'] === 'ysp'){
                that.disabledAudit = true;
              }
            }
          });
        }else{
          this.$nextTick(function() {
            that.form.setFieldsValue({status: '新建',compileTime: Vue.prototype.$formatDate(),contractCategory: 'wz_contract'})
          })
        }
        that.disabledOne = true;
      },
      modalFormOk(record) {
        let that = this;
        if (record && record.id) {
          const newData = [...this.dataSource];
          const target = newData.filter(item => item.id === record.id)[0];
          if(!record['materialCode']){
            record['materialCode']='';
          }else if(!record['materialName']){
            record['materialName']='';
          }else if(!record['assetCategory']){
            record['assetCategory']='';
          }else if(!record['assetName']){
            record['assetName']='';
          }
          newData[newData.indexOf(target)] = record;
          this.dataSource = newData;
        }else{
          record['id'] = '';
          this.dataSource.push(record);
        }
      },
      handleEdit: function (record, params) {
        let contractCategory = this.form.getFieldValue('contractCategory');
        if(contractCategory === 'wz_contract' || contractCategory === 'ticket_contract'){
          this.$refs.materialForm.edit(record, params);
          this.$refs.materialForm.title = "编辑";
          this.$refs.materialForm.disableSubmit = false;
        }else if(contractCategory === 'asset_contract'){
          this.$refs.assetForm.edit(record, params);
          this.$refs.assetForm.title = "编辑";
          this.$refs.assetForm.disableSubmit = false;
        }
      },
      handleAdd: function (params) {
        let contractCategory = this.form.getFieldValue('contractCategory');
        if(contractCategory === 'wz_contract' || contractCategory === 'ticket_contract') {
          this.$refs.materialForm.add(params);
          this.$refs.materialForm.title = "新增";
          this.$refs.materialForm.disableSubmit = false;
        }else if(contractCategory === 'asset_contract'){
          this.$refs.assetForm.add(params);
          this.$refs.assetForm.title = "新增";
          this.$refs.assetForm.disableSubmit = false;
        }
      },
      redirect(id){
        let that = this;
        that.$emit('firstStep')
        that.$emit("nextStep",{id:id,status: ''})
        that.$emit("nextStep",{id:id,status: ''})
      },
      toAudit(){
        let  that = this, id =  this.id;
        this.form.validateFields((err, values) => {
          if (!err) {
            let paramsObject = {contractDetails: this.dataSource}
            for(let i in values){
              this.$set(paramsObject, i, values[i]);
            }
            putAction('/base/mmsContract/auditContractById', paramsObject).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                let result = res.result;
                if (result) {
                  that.redirect(id)
                }
              }else {
                that.$message.warning(res.message);
              }
            })
          }else{
            console.log(err);
            // that.$message.warning(err);
          }
        });
      },
      toSave(){
        let that = this, paramsObject = {contractDetails: this.dataSource}
        this.form.validateFields((err,values)=>{
          if (!err) {
            for (let i in values) {
              this.$set(paramsObject, i, values[i]);
            }
            let action = postAction, url = '/base/mmsContract/addContract';
            if (that.id) {
              paramsObject['id'] = that.id;
            }
            if (paramsObject.hasOwnProperty('id') && paramsObject['id']) {
              url = '/base/mmsContract/addContract';
              action = postAction;
            }
            action(url, paramsObject).then((res) => {
              if (res.success) {
                this.$message.success(res.message);
                // this.$emit('ok');
                let result = res.result;
                if (result) {
                  that.redirect(result['id'])
                }
              } else {
                this.$message.warning(res.message);
                that.redirect(paramsObject['id'])
              }
            }).finally(() => {
            })
          }else{
            // that.$message.warning(err);
          }
        })
      },
      deleteNow(record){
        let that = this;
        this.dataSource.splice(this.dataSource.indexOf(record),1);
      },
      goBack(){
        this.$emit('firstStep')
      },
      initDictConfig(){
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>